package com.mrzhou.core.tool.utils;

import com.mrzhou.core.tool.api.SFunction;
import com.mrzhou.core.tool.constants.StringSymbol;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.util.StringUtils;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;

/**
 * 通用的方法工具类
 */
@Slf4j
public class Func {

    public static String toStr(Object str){
        return toStr(str, "");
    }

    public static String toStr(Object obj, String defaultValue) {
        return null != obj && !obj.equals("null") ? String.valueOf(obj) : defaultValue;
    }

    public static Long toLong(Object obj) {
        String str = toStr(obj);
        try{
            return Long.valueOf(str);
        } catch (Exception e) {
            return null;
        }
    }

    public static Integer toInt(Object obj) {
        String str = toStr(obj);
        try {
            return Integer.valueOf(str);
        } catch (Exception e) {
            log.warn("{}转换Integer失败", obj);
            return null;
        }
    }

    public static boolean toBoolean(String source) {
        if(StringUtils.hasLength(source)) {
            return Boolean.valueOf(source);
        }
        return false;
    }

    public static List<String> toArray(String str) {
        return toArray(str, StringSymbol.COMMA);
    }

    public static List<String> toArray(String str, String split) {
        List<String> array = new ArrayList<>();
        if(StringUtil.isBlank(str)) {
            return array;
        }
        String[] var = str.split(split);
        Stream.of(var).forEach(var1 -> array.add(var1.trim()));
        return array;
    }

    public static List<Long> toLongArray(String str) {
        return toLongArray(str, StringSymbol.COMMA);
    }

    public static List<Long> toLongArray(String str, String split) {
        List<Long> array = new ArrayList<>();
        if(StringUtil.isBlank(str)) {
            return array;
        }
        String[] var = str.split(split);
        Stream.of(var).forEach(var1 -> {
            if(!StringUtil.isNullStr(var1)) {
                array.add(Long.valueOf(var1.trim()));
            }
        });
        return array;
    }

    /**
     * 检查参数列表中是否存在为空的数据
     * @param os
     * @return
     */
    public static boolean hasEmpty(Object... os) {
        int index = os.length;
        for (int i = 0; i < index; i++) {
            Object obj = os[i];
            if(ObjectUtils.isEmpty(obj)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查参数列表是否都为空
     * @param args
     * @return
     */
    public static boolean hasAllEmpty(Object... args) {
        int length = args.length;
        for (int i = 0; i < length; i++) {
            if (ObjectUtils.isNotEmpty(args[i])) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNotEmpty(Object obj) {
        return !ObjectUtils.isEmpty(obj);
    }

    public static boolean isEmpty(Object obj) {
        return ObjectUtils.isEmpty(obj);
    }

    public static boolean isListEmpty(List list) {
        return list == null || list.isEmpty();
    }

    public static boolean isArrayEmpty(Object[] objects) {
        return null == objects || objects.length == 0;
    }

    public static String join(Collection collection) {
        return StringUtils.collectionToCommaDelimitedString(collection);
    }

    /**
     * 获取lambda表达式的对象字段名称
     * @param fn
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> String getColName(SFunction<T, R> fn) {
        // 从function中取出序列化方法
        Method writeReplaceMethod;
        try {
            writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace");
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        // 从序列化方法中取出序列化的lambda信息
        boolean isAccessible = writeReplaceMethod.isAccessible();
        writeReplaceMethod.setAccessible(true);
        SerializedLambda serializedLambda;
        try {
            serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(fn);
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        writeReplaceMethod.setAccessible(isAccessible);
        // 从lambda信息取出method, field, class
        String implMethodName = serializedLambda.getImplMethodName();
        String fieldName = "";
        if (implMethodName.startsWith(SFunction.PREFIX_METHOD_GET)) {
            fieldName = implMethodName.substring(SFunction.PREFIX_METHOD_GET.length());
        } else if (implMethodName.startsWith(SFunction.PREFIX_METHOD_IS)) {
            fieldName = implMethodName.substring(SFunction.PREFIX_METHOD_IS.length());
        }
        fieldName = fieldName.replaceFirst(fieldName.charAt(0) + "", (fieldName.charAt(0) + "").toLowerCase());

        // 尝试
        Field field;
        try {
            field = Class.forName(serializedLambda.getImplClass().replace("/", ".")).getDeclaredField(fieldName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到当前类:" + e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException("未知的属性值: 可能是未使用标准的方式生成get方法:" + e);
        }
        return fieldName;
    }

}
